import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.ArrayList;
import java.util.Iterator;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;


public class main {
	/*
	 * 开工
	 */
	public static boolean isXLSfile(String buff){
		if((buff.length()-4>0)&&(buff.endsWith(".xls"))&&(!buff.equals("out.xls"))){
			return true;
		}
		return false;
	}
	public static void main(String[] args) throws IOException, BiffException, RowsExceededException, WriteException{
		/*
		 * 读取一些设置参数
		 */
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String arg;
		
		System.out.println("使用该程序前请确保所有excel文件已放入当前文件夹:)");
		
		System.out.println("请输入每个分文件从哪一行开始读取");
		arg = br.readLine();
		int SubStartRow = Integer.parseInt(arg)-1;

		System.out.println("请输入表格总共多少列");
		arg = br.readLine();
		int TotalCol = Integer.parseInt(arg);
		
		System.out.println("请输入合并后的文件从哪一行开始");
		arg = br.readLine();
		int MainStartRow = Integer.parseInt(arg)-1;
		
		/*
		 * 定义好要处理的目录
		 */
		File fs = new File("./");
		String test[];
		test = fs.list();
		/*
		 * 定义好输出文件out.xls
		 */
		WorkbookSettings ws = new WorkbookSettings();
		WritableWorkbook workbook = Workbook.createWorkbook(new File("out.xls"));
		WritableSheet s1 = workbook.createSheet("info", 0);
		int currow = MainStartRow;
		
		/*
		 * 开始遍历、合并当前目录下的.xls文件
		 */
		for(int i=0;i<test.length;i++){
			if(isXLSfile(test[i])){
				Workbook tmpwb = Workbook.getWorkbook(new File(test[i]));
				Sheet sheet = tmpwb.getSheet(0);
				loop:
				for(int rr = SubStartRow;;rr++,currow++){
					for(int cc = 0;cc<TotalCol;cc++){
						Cell tmpcell = sheet.getCell(cc,rr);
						String buff = tmpcell.getContents();
						if(buff.isEmpty()&&cc==0)							//如果这一行的起始位置是空的，表明文件结束
							break loop;
						Label label= new Label(cc,currow,buff);
						s1.addCell(label);
					}
				}
			}
		}
		/*
		 * 写完收工
		 */
		workbook.write();
		workbook.close();
		System.out.println("It's done!请检查out.xls:)");
	}
}
